package com.nth.rooster.circles.dao;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.nth.rooster.core.entities.RamCircles;

@Component
public class CircleDAO implements CircleDAOI {
	static Logger LOGGER = Logger.getLogger(CircleDAO.class);

	@Autowired
	private SessionFactory sessionFactory;

	public Long saveAndUpdateCircle(RamCircles circleBeans) {
		LOGGER.debug("Entered::Circle::CircleDAO::createCircle(CircleBeans circleBeans) ");
		Session session = sessionFactory.openSession();
		Transaction transaction = session.getTransaction();
		transaction.begin();
		if (circleBeans.getCircleID() == null) {
			session.save(circleBeans);
		}else{
			session.update(circleBeans);
		}
		transaction.commit();
		session.close();
		LOGGER.debug("Exited::Circle::CircleDAO::createCircle(CircleBeans circleBeans) ");
		
		return circleBeans.getCircleID();
	}

	public RamCircles getCircleByCircleID(Long id) {
		LOGGER.debug("Entered::Circle::CircleDAO::getCircleByCircleID()");
		Session session = sessionFactory.openSession();
		Query query = session
				.createQuery("from RamCircles where circleID=:circleID");
		query.setLong("circleID", id);

		RamCircles circles = (RamCircles) query.uniqueResult();
		session.close();
		LOGGER.debug("Exited::Circle::CircleDAO::getCircleByCircleID()");
		return circles;
	}

	public List<RamCircles> getAllCircles() {
		LOGGER.debug("Entered::Circle::CircleDAO::getAllCircles()");
		Session session = sessionFactory.openSession();
		Query query = session.createQuery("from RamCircles");
		List<RamCircles> circles = query.list();
		session.close();
		LOGGER.debug("Exited::Circle::CircleDAO::getAllCircles()");
		return circles;
	}

}
